本文整理匯總了Golang中github.com/gin-gonic/gin.Context.ClientIP方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.ClientIP方法的具體用法?Golang Context.ClientIP怎麽用?Golang Context.ClientIP使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.ClientIP方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Logger
func Logger(c *gin.Context) {
requestId := util.NewId()
c.Set("request_id", requestId)
method := c.Request.Method
path := c.Request.URL.EscapedPath()
ip := c.ClientIP()
log.InfoFields("Request received", log.Fields{
"request_id": requestId,
"method": method,
"ip": ip,
"path": path,
})
start := time.Now()
c.Next()
duration := time.Since(start)
code := c.Writer.Status()
log.InfoFields("Request handled", log.Fields{
"request_id": requestId,
"took": duration.String(),
"code": code,
})
}
示例2: SignInPost
func SignInPost(c *gin.Context) {
db := models.GetDB()
session := sessions.Default(c)
login := &models.Login{}
if c.Bind(login) == nil {
user := &models.User{}
db.Where("lower(email) = lower(?)", login.Email).First(user)
if user.ID == 0 {
log.Printf("ERROR: Login failed, IP: %s, Email: %s\n", c.ClientIP(), login.Email)
session.AddFlash("Эл. адрес или пароль указаны неверно")
session.Save()
c.Redirect(303, "/signin")
return
}
//create user
if err := user.ComparePassword(login.Password); err != nil {
log.Printf("ERROR: Login failed, IP: %s, Email: %s\n", c.ClientIP(), login.Email)
session.AddFlash("Эл. адрес или пароль указаны неверно")
session.Save()
c.Redirect(303, "/signin")
return
}
session.Set("user_id", user.ID)
session.Save()
c.Redirect(303, "/")
}
}
示例3: SignInPost
//SignInPost handles POST /signin route, authenticates user
func SignInPost(c *gin.Context) {
session := sessions.Default(c)
user := &models.User{}
if err := c.Bind(user); err != nil {
session.AddFlash("Please, fill out form correctly.")
session.Save()
c.Redirect(http.StatusFound, "/signin")
return
}
userDB, _ := models.GetUserByEmail(user.Email)
if userDB.ID == 0 {
logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
session.AddFlash("Email or password incorrect")
session.Save()
c.Redirect(http.StatusFound, "/signin")
return
}
if err := bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password)); err != nil {
logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
session.AddFlash("Email or password incorrect")
session.Save()
c.Redirect(http.StatusFound, "/signin")
return
}
session.Set("UserID", userDB.ID)
session.Save()
c.Redirect(http.StatusFound, "/")
}
示例4: view
func view(c *gin.Context) {
id := c.Param("uniuri")
key := c.Param("key")
re := models.ResourceEntry{}
remote := c.ClientIP()
db.Where(&models.ResourceEntry{Key: id}).First(&re)
if re.Key == "" {
log.Printf("[INFO][%s]\tNot found : %s", remote, id)
c.AbortWithStatus(http.StatusNotFound)
return
}
log.Printf("[INFO][%s]\tFetched %s file and entry\n", remote, id)
f, err := os.Open(path.Join(conf.C.UploadDir, re.Key))
if err != nil {
log.Printf("[ERROR][%s]\tWhile opening %s file\n", remote, id)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
var iv [aes.BlockSize]byte
stream := cipher.NewCFBDecrypter(block, iv[:])
reader := &cipher.StreamReader{S: stream, R: f}
c.Header("Content-Disposition", "filename=\""+re.Name+"\"")
io.Copy(c.Writer, reader)
}
示例5: index
func index(c *gin.Context) {
log.Printf("[INFO][%s]\tIssued a GET request\n", c.ClientIP())
if conf.C.FullDoc {
c.HTML(http.StatusOK, "index.html", gin.H{})
} else {
c.HTML(http.StatusOK, "welcome.html", gin.H{})
}
}
示例6: putFile
func putFile(c *gin.Context) {
if isIPBanned(c.ClientIP()) {
c.Data(200, "text/plain", []byte("You are rate limited to 20 requests/hour."))
return
}
filename := c.Param("title")
if len(filename) == 0 {
filename = randomAlliterateCombo()
}
contentLength := c.Request.ContentLength
var reader io.Reader
reader = c.Request.Body
if contentLength == -1 {
// queue file to disk, because s3 needs content length
var err error
var f io.Reader
f = reader
var b bytes.Buffer
n, err := io.CopyN(&b, f, _24K+1)
if err != nil && err != io.EOF {
log.Printf("%s", err.Error())
}
if n > _24K {
file, err := ioutil.TempFile("./", "transfer-")
if err != nil {
log.Printf("%s", err.Error())
}
defer file.Close()
n, err = io.Copy(file, io.MultiReader(&b, f))
if err != nil {
os.Remove(file.Name())
log.Printf("%s", err.Error())
}
reader, err = os.Open(file.Name())
} else {
reader = bytes.NewReader(b.Bytes())
}
contentLength = n
}
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
// p := WikiData{filename, "", []string{}, []string{}, false, ""}
// p.save(buf.String())
var p WikiData
p.load(strings.ToLower(filename))
p.save(buf.String())
c.Data(200, "text/plain", []byte("File uploaded to http://"+RuntimeArgs.ExternalIP+"/"+filename))
}
示例7: GetIP
// GetIP : just get the client ip
func GetIP(c *gin.Context) (ip net.IP, err error) {
tmp := c.ClientIP()
ipStr, _, err := net.SplitHostPort(tmp)
ip = net.ParseIP(ipStr)
if err != nil {
logger.Error("Client IP fail , %s", err)
return nil, err
}
return ip, nil
}
示例8: PushBuildLogs
// PushBuildLogs pushes the updated build logs.
func PushBuildLogs(c *gin.Context) {
var (
owner = c.Param("owner")
name = c.Param("name")
number = c.Param("build")
job = c.Param("job")
)
io.Copy(c.Writer, c.Request.Body)
log.Printf("Agent %s pushed logs for %s/%s#%s.%s", c.ClientIP(), owner, name, number, job)
}
示例9: GetSubjects
func (m *Mongo) GetSubjects(c *gin.Context) {
var subject []models.Subject
log.Println(c.ClientIP())
subject = new(models.Subject).Get(m.Database)
c.JSON(http.StatusOK, gin.H{
"err": false,
"subjects": subject,
})
}
示例10: GetTags
func (m *Mongo) GetTags(c *gin.Context) {
var tag []models.Tags
log.Println(c.ClientIP())
tag = new(models.Tags).Get(m.Database)
c.JSON(http.StatusOK, gin.H{
"err": false,
"tags": tag,
})
}
示例11: create
func create(c *gin.Context) {
var err error
remote := c.ClientIP()
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.LimitSize*1000000)
fd, h, err := c.Request.FormFile("file")
if err != nil {
log.Printf("[ERROR][%s]\tDuring reading file : %s", remote, err)
c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.LimitSize)
c.AbortWithStatus(http.StatusRequestEntityTooLarge)
return
}
defer fd.Close()
u := uniuri.NewLen(conf.C.UniURILength)
k := uniuri.NewLen(16)
kb := []byte(k)
block, err := aes.NewCipher(kb)
if err != nil {
log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
var iv [aes.BlockSize]byte
stream := cipher.NewCFBEncrypter(block, iv[:])
path := path.Join(conf.C.UploadDir, u)
file, err := os.Create(path)
if err != nil {
log.Printf("[ERROR][%s]\tDuring file creation : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer file.Close()
writer := &cipher.StreamWriter{S: stream, W: file}
// No encryption : wr, err := io.Copy(file, bufio.NewReaderSize(fd, 512))
// Copy the input file to the output file, encrypting as we go.
wr, err := io.Copy(writer, bufio.NewReaderSize(fd, 512))
if err != nil {
log.Printf("[ERROR][%s]\tDuring writing : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
}
db.Create(&models.ResourceEntry{Key: u, Name: h.Filename})
log.Printf("[INFO][%s]\tCreated %s file and entry (%v bytes written)\n", remote, u, wr)
c.String(http.StatusCreated, "https://%s/v/%s/%s\n", conf.C.NameServer, u, k)
}
示例12: rateLimit
func rateLimit(c *gin.Context) {
ip := c.ClientIP()
value := int(ips.Add(ip, 1))
if value%50 == 0 {
fmt.Printf("ip: %s, count: %d\n", ip, value)
}
if value >= 200 {
if value%200 == 0 {
fmt.Println("ip blocked")
}
c.Abort()
c.String(503, "you were automatically banned :)")
}
}
示例13: PushBuild
// PushBuild pushes the updated build.
func PushBuild(c *gin.Context) {
var (
owner = c.Param("owner")
name = c.Param("name")
number = c.Param("build")
job = c.Param("job")
)
work := new(queue.Work)
if err := c.BindJSON(work); err != nil {
log.Printf("Invalid JSON input. %s", err)
c.String(500, "Invalid JSON input. %s", err)
return
}
c.JSON(200, work)
log.Printf("Agent %s pushed update for %s/%s#%s.%s %s",
c.ClientIP(), owner, name, number, job, work.Job.Status)
}
示例14: apiLog
func apiLog(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
// before request
c.Next()
// after request
end := time.Now()
latency := end.Sub(start)
status := c.Writer.Status()
client := c.ClientIP()
method := c.Request.Method
log.Infof("%v %v %v %v %v",
latency, client, method, path, status)
}
示例15: Stream
// Stream streams the logs to disk or memory for broadcasing to listeners. Once
// the stream is closed it is moved to permanent storage in the database.
func Stream(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.String(500, "Invalid input. %s", err)
return
}
key := c.Param("id")
logrus.Infof("Agent %s creating stream %s.", c.ClientIP(), key)
wc, err := stream.Writer(c, key)
if err != nil {
c.String(500, "Failed to create stream writer. %s", err)
return
}
defer func() {
wc.Close()
stream.Delete(c, key)
}()
io.Copy(wc, c.Request.Body)
rc, err := stream.Reader(c, key)
if err != nil {
c.String(500, "Failed to create stream reader. %s", err)
return
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer recover()
store.WriteLog(c, &model.Job{ID: id}, rc)
wg.Done()
}()
wc.Close()
wg.Wait()
c.String(200, "")
logrus.Debugf("Agent %s wrote stream to database", c.ClientIP())
}