Gin is a web framework written in Golang. It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
thinkerou on go_modules
type MyModel struct {
key string `json:"key" bindind:"dafult=5"`
}
How to use a type definition in another file with swaggo?
Using swaggo generate API document based on godoc
syntax.
Source folder and files
|-post
|--controller.go
|--response.go
For this definition:
controller.go
package post
...
// Index godoc
// @Summary Index Post
// @Success 200 {array} []*Response
// @Router /v1/posts [get]
func Index(ctx *gin.Context) {
...
}
The Response
is been defined in an another file but the same package.
response.go
package post
// Response is post response body
type Response struct {
ID int64 `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
But when run swag init
to generate swagger docs, it said:
2021/01/29 09:39:56 Generate swagger docs....
2021/01/29 09:39:56 Generate general API Info, search dir:./
2021/01/29 09:39:56 ParseComment error in file application/post/controller.go :cannot find type definition:
When I move the Response
struct to controller.go
, it works.
How to import it with godoc or swaggo?
Hi @Antonin72982395_twitter , I don't think you can have default values just like that, but you can do something like below
func NewResponse(data interface{}) Response {
// ... check nil and assign default values
}
or as an extension function
func (r *Response) SetDefaults() Response {
// ... check nil and assign default values
}
sess := r.Group("/", pkg.EnableCookieSession())
{
sess.POST("/login", post.Login)
/*
* Got problem here, session not working...
*/
authorized := sess.Group("/auth", pkg.AuthSessionMiddle)
// authorized := sess.Group("/auth")
{
authorized.POST("/upload", post.Upload)
authorized.POST("/webshell", post.WebShell)
authorized.StaticFS("/download", http.Dir("download"))
}
}
err := r.Run(":3333")
// err := r.RunTLS(":3333", "server.crt", "server.key")
if err != nil {
log.Fatal("r.Run")
}
func Login(c *gin.Context) {
tableName := "user_passwd"
username := c.PostForm("username")
password := c.PostForm("password")
passwordMd5Form := fmt.Sprintf("%x", md5.Sum([]byte(password)))
db, err := sql.Open("mysql", "root:hushanglai@tcp(localhost:3306)/web")
if err != nil {
log.Printf("sql.Open: %v", err)
}
defer func(db *sql.DB) {
err := db.Close()
if err != nil {
log.Printf("Fail to close db:%v", err)
}
}(db)
// Query password for a specified username
sqlString := fmt.Sprintf("select password from %s where username=\"%s\"",
tableName, username)
res, err := db.Query(sqlString)
defer func(res *sql.Rows) {
err := res.Close()
if err != nil {
log.Printf("res.Close: %v", err)
}
}(res)
if err != nil {
log.Printf("db.Query: %v", err)
}
var passwordMd5Mysql string
for res.Next() {
err = res.Scan(&passwordMd5Mysql)
if err != nil {
c.String(http.StatusUnauthorized, "username or password wrong!")
}
}
if passwordMd5Mysql != passwordMd5Form {
c.String(http.StatusUnauthorized, "username or password wrong!")
return
}
c.String(http.StatusOK, "Login successful")
pkg.SaveAuthSession(c, username)
c.JSON(http.StatusOK, gin.H{"message": "Successfully authenticated user"})
}
func SaveAuthSession(c *gin.Context, username string) {
session := sessions.Default(c)
session.Set("user", username)
err := session.Save()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save session"})
}
c.JSON(http.StatusOK, gin.H{"message": "save session ok"})
}
My pkg.AuthSessionMiddle function,
func AuthSessionMiddle(c *gin.Context) {
session := sessions.Default(c)
sessionValue := session.Get("user")
if sessionValue == nil {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized",
})
c.Abort()
return
}
// c.Set("userId", sessionValue.(uint))
c.Next()
return
}
My problem is here, sessionValue := session.Get("user") won't get the session, I don't know why.
err = autotls.Run(r, "api.myvaliddomain.com")
Go Gin reCAPTCHA Example (v2 & v3)