go-swagger with path param - go

Route:
// swagger:route DELETE /v1/path/{id} api DeleteV1
//
// Deletes an item.
//
// Schemes: https
//
// Responses:
// 202: AcceptedResponse
// 401: UnauthorizedErrorResponse
// 500: InternalServerErrorResponse
"/v1/path/{id}": {
"DELETE": Handle(DeleteRequest{}),
"OPTIONS": s.handleOptionsRequest,
},
Params/response model:
// Description
//
// swagger:parameters DeleteV1
type DeleteRequest struct {
// id of an item
//
// In: path
id string `json:"id"`
cookies []*http.Cookie
}
// Description
//
// swagger:response DeleteResponse
type DeleteResponse struct {
}
I keep getting - path param "{id}" has no parameter definition whatever I try.
The endpoint takes only path param "id", cookies (they are not visible in a swagger model) and returns an empty body and an HTTP status code.
How to make go-swagger see the "parameter definition"for the "{id}"?

The struct field needs to be exported. Try:
type DeleteRequest struct {
// ID of an item
//
// In: path
ID string `json:"id"`

Related

gin how to check whether params was post or not

type listParams struct {
Status int `form:"status"`
Keyword string `form:"keyword"`
ShowType int `form:"show_type"`
}
func List(c *gin.Context) {
var ReqData listParams
_ = c.ShouldBind(&ReqData)
// I fetch this by PostForm() to check it empy if it equal to empty string
if stat := c.PostForm("status"); stat == "" {
ReqData.Status = -99
}
// .......
}
In this code, How can I know that was front-end post the status or not?
Because of the default value of go, if I check the reqData.Status == 0, it will always return true if the front-end didn't post it, but In my case, 0 is a meaningful value, So I can't check it by equal to 0.
So am I have the others way to check it?
PS: I tried and found out that gorm will not update the field in struct if I don't assign:
var d &User{} // User is a definition of user table
d.ID = 1
d.Name = "Joy"
// d.Status = 1 // It has this field, but I dont assign it
db.Model(&User{}).updates(&d)
Finally, status won't update to 0(In my understanding, d.Status should be 0)
Use a pointer type to circumvent the 0 default value:
type listParams struct {
Status &int `form:"status"`
Keyword string `form:"keyword"`
ShowType int `form:"show_type"`
}
The check if d.Status is nil, otherwise get the associated value
I think this constraint raises the need for having a sole public way to construct User.
type user struct { Status int Keyword string ShowTypeint}
func NewUser() (*user) { return &user{Status: -1} }
That way you ensure that user struct is only constructed through NewUser having Status default value Status always equal to -1.

SwiftUI access passed view data in sctruct header

How can I pass data to a view and use it directly in the "header"? All tutorials I made are accessing the data in the view body - which works fine - but I want to call a graphlql method from the UpdateAccountView and than render a view based on the result.
My class for passing data:
class Account {
var tel: Int
init(tel: Int) {
self.tel = tel
}
}
My main view where the class is initialised (simplified - normally the "tel" will come from an input)
struct ContentView: View {
var account: Account = Account(tel: 123)
var body: some View {
NavigationView {
NavigationLink(
destination: UpdateAccountView(account: account),
label: {
Text("Navigate")
})
}
}
}
The view I call to do the request and call the next view based on the result
UpdateAccount is taking tel:Int as a parameter.
And here is the problem. I cannot access account.tel from the passed data.
struct UpdateAccountView: View {
var account: Account
#ObservedObject private var updateAccount: UpdateAccount = UpdateAccount(tel: account.tel)
#ViewBuilder
var body: some View {
if updateAccount.success {
AccountVerifyView()
} else {
ContentView()
}
}
}
The error:
Cannot use instance member 'account' within property initializer; property initializers run before 'self' is available
Update method (GraphQL):
class UpdateAccount: ObservableObject {
#Published var success: Bool
init(tel: Int){
self.success = false
update(tel: tel)
}
func update(tel: Int){
Network.shared.apollo.perform(mutation: UpdateAccountMutation(tel: tel)) { result in
switch result {
case .success(let graphQLResult):
self.success = graphQLResult.data!.updateAccount.success
case .failure(let error):
print("Failure! Error: \(error)")
self.success = false
}
}
}
I saw that there is an EnvironmentObject but than the variable become available globally as far as I understood, which is not necessary here.
Thank you for your help.
You can make it in explicit init, like
struct UpdateAccountView: View {
var account: Account
#ObservedObject private var updateAccount: UpdateAccount // << declare
init(account: Account) {
self.account = account
self.updateAccount = UpdateAccount(tel: account.tel) // << here !!
}
// ... other code
}

How to perform conditional required validation ussing ozzo validation in golang?

In Golang ozzo-validation, how can I validate a field which is dependent on another field ?
For example, if I have the following:
return validation.ValidateStruct(&c,
validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),
validation.Field(&c.Gender, validation.In("Female", "Male")),
validation.Field(&c.Email, is.Email),
validation.Field(&c.Address),
How can I add a validation that the Address is required only if email is not empty?
You can achieve it in two ways-
Adding your own custom rules
Conditionally add FieldRules based on precondition-value i.e check Email while creating field rules then supply it to validation.ValidateStruct
For e.g.:
type Sample struct {
Name string
Gender string
Email string
Address Address
}
type Address struct {
// ... fields
}
func (s Sample) Validate() error {
var fieldRules []*validation.FieldRules
fieldRules = append(fieldRules, validation.Field(&s.Name, validation.Required, validation.Length(5, 20)))
fieldRules = append(fieldRules, validation.Field(&s.Gender, validation.In("Female", "Male")))
fieldRules = append(fieldRules, validation.Field(&s.Email, is.Email))
if len(strings.TrimSpace(s.Email)) > 0 {
fieldRules = append(fieldRules, validation.Field(&s.Address, validation.Required))
fieldRules = append(fieldRules, validation.Field(&s.Address))
}
return validation.ValidateStruct(&s, fieldRules...)
}
The library now supports conditional validation by the validation.When function.
Here is a code snipped which fits the validation you described.
package main
import (
"fmt"
validation "github.com/go-ozzo/ozzo-validation" // or "github.com/go-ozzo/ozzo-validation/v4" if "When" not found
)
type Entry struct {
Name string
Gender string
Email string
Address string
}
func main() {
v := func(e Entry) {
fmt.Println(validation.ValidateStruct(&e,
validation.Field(&e.Name, validation.Required, validation.Length(5, 20)),
// Note that if gender is "" and not required, validation returns no error.
validation.Field(&e.Gender, validation.Required, validation.In("Female", "Male")),
validation.Field(&e.Address, validation.When(e.Email != "", validation.Required.Error("Address is required if Email is set"))),
))
}
// All is fine for no Email.
e := Entry{
Name: "My name is!",
Gender: "Male",
}
v(e)
// Validation fails for Email and no Address.
e = Entry{
Name: "My name is!",
Gender: "Male",
Email: "a#org.com",
}
v(e)
}
It outputs.
<nil>
Address: Address is required if Email is set.
The library documentation describes it as well: https://github.com/go-ozzo/ozzo-validation#conditional-validation

How can I create class in swift 3 for my custom message that conforms to JSQMessageData?

I am not familiar with Objective-C so I am not able to understand this.
My message structure is different than JSQMessage so I want to create my own class.
Here is my class
class ChatMessage:NSObject {
var createdAt:Double?
var createdName:String?
var createdUid:String?
var imageUrl:String?
var name:String?
var text:String?
var uColor:String?
var uid:String?
}
If you're implementing this in Swift, and you want to make it usable within that framework, you should make your class conform to JQMessageData. You just need to implement the required methods and variables.
class ChatMessages: NSObject, JSQMessageData {
// MARK: Required methods
func senderId() -> String! {
// your code here, return a unique ID for your sender
}
func senderDisplayName() -> String! {
// your code here, return the display name of your sender
}
func date() -> Date! {
// your code here, return your message date
}
func isMediaMessage() -> Bool {
// your code here, return whether your message contains media
}
func messageHash() -> UInt {
// your code here, return a unique identifier for your message
}
// MARK: Optional methods
func text() -> String! {
// your code here, return your message text
}
func media() -> JSQMessageMediaData! {
// your code here, return your message media if required
}
// MARK: Other methods and variables
// ...
}
Check the documentation for what to return in those methods.

How can I embed an initialized variable in a struct?

Is there a good way to embed initialized struct variables in another struct?
Consider the following situation:
type Account struct {
AdminUser, AdminPass string
}
const (
acc1: "account_user",
pass: "111222"
)
var AccountDef = Account {
AdminUser: "acc1",
AdminPass: "pass1"
}
type Login struct {
Acc *AccountDef
Username, Password, Token string
}
var LoginDef = Login {
Token: "adaasdasddas1123"
}
I want to reuse AccountDef in Login, then I want to instantiate LoginDef in another function then use it for rendering templates like LoginDef.Acc.AdminUser
Is this possible to do?
If you want a Login to contain the fields from an Account, you can embed them like so:
http://play.golang.org/p/4DXnIsILd6
type Account struct {
AdminUser string
AdminPass string
}
type Login struct {
*Account
Username, Password, Token string
}
func main() {
acct := &Account{
AdminUser: "username",
AdminPass: "pass",
}
login := Login{Account: acct}
fmt.Println("login.AdminUser:", login.AdminUser)
fmt.Println("login.AdminPass:", login.AdminPass)
}

Resources