package main
import ( "context" "github.com/gin-gonic/gin" "github.com/redis/go-redis/v9" "net/http" "strconv" )
type Student struct { Name string Age int Height float32 }
func GetStudentInfo(studentId string) Student { client := redis.NewClient(&redis.Options{ Addr: "172.16.136.8:6379", Password: "123456", DB: 0, }) ctx := context.TODO() stu := Student{} for field, value := range client.HGetAll(ctx, studentId).Val() { if field == "Name" { stu.Name = value } else if field == "Age" { age, err := strconv.Atoi(value) if err != nil { stu.Age = age } } else if field == "Height" { height, err := strconv.ParseFloat(value, 10) if err != nil { stu.Height = float32(height) } } } return stu }
func GetAge(ctx *gin.Context) { parm := ctx.PostForm("student_id") if len(parm) == 0 { ctx.String(http.StatusBadRequest, "please indidate the student id") return } stu := GetStudentInfo(parm) ctx.String(http.StatusOK, strconv.Itoa(stu.Age)) return }
func GetName(ctx *gin.Context) { parm := ctx.Query("student_id") if len(parm) == 0 { ctx.String(http.StatusBadRequest, "please indidate the student id") return } stu := GetStudentInfo(parm) ctx.String(http.StatusOK, stu.Name) return }
func main() { engine := gin.Default() engine.GET("/get_name", GetName) engine.POST("./get_age", GetAge) err := engine.Run("0.0.0.0:2345") if err != nil { panic(err) } }
|