英文:
how to have Go accept web requests
问题
在Go语言中,你可以使用net包来处理HTTP请求并提供输出,比如JSON。你可以监听80端口来捕获http://api.example.com/users/42
这样的请求,并进行相应的处理。
以下是一个简单的示例代码,演示了如何在Go中处理HTTP请求并返回JSON输出:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
http.HandleFunc("/users/", handleUserRequest)
log.Fatal(http.ListenAndServe(":80", nil))
}
func handleUserRequest(w http.ResponseWriter, r *http.Request) {
// 解析URL路径参数
id := r.URL.Path[len("/users/"):]
// 创建用户对象
user := User{
ID: id,
Name: "John Doe",
}
// 将用户对象转换为JSON
jsonData, err := json.Marshal(user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 设置响应头
w.Header().Set("Content-Type", "application/json")
// 返回JSON数据
fmt.Fprint(w, string(jsonData))
}
在上面的示例中,我们使用http.HandleFunc
函数将/users/
路径与handleUserRequest
函数关联起来。当收到以/users/
开头的请求时,该函数会解析URL路径参数,创建一个用户对象,并将其转换为JSON格式的数据返回给客户端。
你可以根据自己的需求修改handleUserRequest
函数来处理不同的请求和输出。希望这可以帮助到你!
英文:
I don't have the exact terminology so stay with me.
For php when a request comes in, say to http://api.example.com/users/42
, Apache redirects the request to the appropriate directory.
In Go, how would I capture the http://api.example.com/users/42
and then serve the output, such as JSON? Would I use the net package and listen on port 80?
I'm sure this is pretty elementary, but I don't think I have the correct terminology hence why it's a little hard to look up.
答案1
得分: 2
我强烈推荐阅读维基百科,特别是这篇
文章,还可以查看这本优秀的书籍:使用Golang构建Web应用程序
基本思路是:
package main
func main() {
http.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
})
http.ListenAndServe(":80", nil)
}
请注意,要监听端口80
,您需要以root权限运行。
英文:
I highly recommend reading the Wiki, specially this
article, also check this excelent book : Build Web Application with Golang
basic idea is :
package main
func main() {
http.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
})
http.ListenAndServe(":80", nil)
}
Note that to listen on port 80
you have to be root.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论