douou6807 2019-07-20 14:26
浏览 120
已采纳

如何从HTTP处理程序中的URL获取参数

I'm working on a web service application with endpoint/crypto/rates accepting as an input two “symbols” of currencies. The web service should search for currency exchange data between these characters in the database, and if there is no value in the database, or the timestamp value differs from the current by more than 1 minute, make a request to the service API: https://min-api.cryptocompare.com/documentation So, I created the struct and the go-chi router. But I don't know how to build a working handler to get parameters from URL, for example: https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD

package main

import (
    "github.com/go-chi/chi"
    "net/http"
)

type Crypto struct {
    Cur1 string
    Cur2 string
    Rate float64
    Timestamp int64
}
func main() {
    port := ":3000"
    r := chi.NewRouter()
    r.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Connected"))
    })

    http.ListenAndServe(port, r)

I think I can try to create Cur1 for first value on the handler body:

cur1 = r.FormValue("cur1")

Similarly for second value:

Cur2 = r.FormValue("cur2") 

The final request will be: ~/get_rates?cur1=eth&cur2=btc

  • 写回答

1条回答 默认 最新

  • dpxyfa4718 2019-07-20 15:21
    关注

    You can extract query params from a request by calling the getter r.URL.Query().Get("paramName")

    Extracting cur1 and cur2 for your task will be something like that:

    r.Get("/get_rates", func(w http.ResponseWriter, r *http.Request) {
            cur1 := r.URL.Query().Get("cur1")
            cur2 := r.URL.Query().Get("cur2")
            w.Write([]byte("cur1=" + cur1 + "; cur2=" + cur2))
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧