如何让Go接受网络请求

huangapple go评论133阅读模式
英文:

how to have Go accept web requests

问题

在Go语言中,你可以使用net包来处理HTTP请求并提供输出,比如JSON。你可以监听80端口来捕获http://api.example.com/users/42这样的请求,并进行相应的处理。

以下是一个简单的示例代码,演示了如何在Go中处理HTTP请求并返回JSON输出:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. )
  8. type User struct {
  9. ID int `json:"id"`
  10. Name string `json:"name"`
  11. }
  12. func main() {
  13. http.HandleFunc("/users/", handleUserRequest)
  14. log.Fatal(http.ListenAndServe(":80", nil))
  15. }
  16. func handleUserRequest(w http.ResponseWriter, r *http.Request) {
  17. // 解析URL路径参数
  18. id := r.URL.Path[len("/users/"):]
  19. // 创建用户对象
  20. user := User{
  21. ID: id,
  22. Name: "John Doe",
  23. }
  24. // 将用户对象转换为JSON
  25. jsonData, err := json.Marshal(user)
  26. if err != nil {
  27. http.Error(w, err.Error(), http.StatusInternalServerError)
  28. return
  29. }
  30. // 设置响应头
  31. w.Header().Set("Content-Type", "application/json")
  32. // 返回JSON数据
  33. fmt.Fprint(w, string(jsonData))
  34. }

在上面的示例中,我们使用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应用程序

基本思路是:

  1. package main
  2. func main() {
  3. http.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
  4. w.Write([]byte("Hello"))
  5. })
  6. http.ListenAndServe(":80", nil)
  7. }

请注意,要监听端口80,您需要以root权限运行。

英文:

I highly recommend reading the Wiki, specially this article, also check this excelent book : Build Web Application with Golang

basic idea is :

  1. package main
  2. func main() {
  3. http.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
  4. w.Write([]byte("Hello"))
  5. })
  6. http.ListenAndServe(":80", nil)
  7. }

Note that to listen on port 80 you have to be root.

huangapple
  • 本文由 发表于 2014年4月29日 05:30:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/23351518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定