rest - 去lang net/http请求模式

标签 rest go

我正在编写一个简单的rest api服务器,但无法使用net / http获取路由动态url

  • http://localhost:8080/book/ 名称

  • 其中名称可以是任何字符串。

    这是我的尝试:
    func viewIndex(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, 'html')
    }
    
    http.HandleFunc("/book/{name}", view)
    

    这不起作用, HandleFunc 的文档中有一些神秘的注释:

    ServeMux的文档说明了如何匹配模式。

    最佳答案

    这是一个可行的解决方案。
    它唯一以 / 结尾的模式将被视为所有URL的前缀匹配器。

    因此, / book / 模式将匹配:

  • / book /
  • / book / a
  • / book / bb
  • / book / a / b

  • 示例简化代码:
    package main
    
    import (
            "fmt"
            "strings"
            "net/http"
    )
    
    func book(name string) {
      fmt.Printf("requesting book '%s'\n",name);
    }
    
    func view(w http.ResponseWriter, r *http.Request) {
        url := r.URL.String()
        if strings.HasPrefix(url, "/book/"){
          name := url[6:]
          book(name)
          fmt.Fprint(w, name)
        }
    }
    
    func main() {
      http.HandleFunc("/book/", view)
      http.ListenAndServe("localhost:8080", nil)
    }
    

    关于rest - 去lang net/http请求模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62338665/

    相关文章:

    java - Jersey REST : Importing headers from a Map into a WebResource instance

    rest - REST 中依赖资源的设计模式

    rest - 对于损坏的有效负载(校验和失败),最合适的 HTTP 错误代码是什么?

    utf-8 - 在 Go 中使用 C 库时,如何正确地将 UTF-8 编码的字符数组转换为 Go 字符串?

    linux - 在 darwin for linux 上交叉编译 CGO 应用程序

    rest - 在数据库中发现错误数据的 HTTP 响应状态代码

    java.lang.AssertionError : expected:<200> but was:<404> in jersey restful services unit test

    go - 即使我不做任何更改,我的 go 代码也会返回不同的结果

    Golang TLS 握手错误 - "first record does not look like a TLS handshake"?

    golang gin 加载 html 超时