Skip to content

Instantly share code, notes, and snippets.

@craftslab
Last active May 3, 2021 03:20
Show Gist options
  • Save craftslab/96961804a449d6bd05aac5ba134ea1cb to your computer and use it in GitHub Desktop.
Save craftslab/96961804a449d6bd05aac5ba134ea1cb to your computer and use it in GitHub Desktop.
hello gin
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"log"
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowCredentials: true,
AllowHeaders: []string{"Origin", "Authorization", "Content-Type"},
AllowMethods: []string{"DELETE", "GET", "PATCH", "POST", "PUT"},
AllowOrigins: []string{"*"},
AllowOriginFunc: func(origin string) bool {
return true
},
ExposeHeaders: []string{"Content-Type"},
MaxAge: 24 * time.Hour,
}))
router.POST("/auth/login", loginEndpoint)
if err := router.Run(":9090"); err != nil {
log.Fatalf("failed to run: %v", err)
}
}
func loginEndpoint(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "Hello Gin!",
})
}
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const axios = require('axios')
async function postRequest() {
axios.post('http://localhost:9090/auth/login', {
username: 'admin',
password: 'admin'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then (function (resp) {
console.log(`Data: ${resp.data.message}`)
console.log(`Date: ${resp.headers.date}`)
console.log(`Path: ${resp.request.path}`)
console.log(`Request method: ${resp.request.method}`)
console.log(`Status code: ${resp.status}`)
console.log(`Status text: ${resp.statusText}`)
})
.catch (error => {
console.log(error)
})
}
postRequest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment