MST

星途 面试题库

面试题:Go语言匿名函数在简单事件处理中的应用

假设有一个简单的Web服务器,当接收到特定路径的GET请求时,需要执行一段特定的逻辑。请使用Go语言的匿名函数来实现这个事件处理逻辑,示例路径为 "/hello",处理逻辑为返回一段固定的欢迎消息。请写出完整的代码片段。
30.6万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        if r.Method == "GET" {
            fmt.Fprintf(w, "欢迎访问!")
        }
    })
    fmt.Println("Server is running on http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}