package main
import (
"encoding/json"
"fmt"
"log"
)
type TemplateCategory struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Template struct {
Name string `json:"name"`
CategoryInfo *TemplateCategory `json:"category_info"`
}
func (t *Template) UnmarshalJSON(b []byte) error {
var result map[string]interface{}
if err := json.Unmarshal(b, &result); err != nil {
return err
}
if t == nil {
t = &Template{}
}
t.Name, _ = result[`name`].(string)
categoryInfo, isMap := result[`category_info`].(map[string]interface{})
if isMap {
t.CategoryInfo = &TemplateCategory{}
t.CategoryInfo.ID, _ = categoryInfo[`id`].(int)
t.CategoryInfo.Name, _ = categoryInfo[`name`].(string)
}
return nil
}
func main() {
json1 := []byte(`{
"name": "Мой шаблон",
"category_info": {
"id": 109,
"name": "Тест"
}
}`)
json2 := []byte(`{
"name": "Мой шаблон",
"category_info": []
}`)
var data1 Template
err := json.Unmarshal(json1, &data1)
if err != nil {
log.Fatalf(`json1: %s`, err)
}
var data2 Template
err = json.Unmarshal(json2, &data2)
if err != nil {
log.Fatalf(`json2: %s`, err)
}
fmt.Printf("data1: %+v\n", data1)
fmt.Printf("data1.CategoryInfo: %+v\n\n", data1.CategoryInfo)
fmt.Printf("\n\ndata2: %+v\n", data2)
fmt.Printf("data2.CategoryInfo: %+v\n\n", data2.CategoryInfo)
}
die ( mysql_error () );
последние 10 лет программилна зоне программил с отсутствием интернета?
const createSetAuthInterceptor = options => config => {
if (options.access) {
config.headers.Authorization = options.access;
} else {
delete config.headers.Authorization;
}
return config;
};
const setAuthCb = createSetAuthInterceptor(store.state.auth);
axios.interceptors.request.use(setAuthCb);
let refreshTokenPromise;
const createUpdateAuthInterceptor = (store, http) => async error => {
const message = get(error, 'response.data.message');
if (!['Token expired', 'Invalid token'].includes(message)) {
return Promise.reject(error);
}
if (!refreshTokenPromise) {
refreshTokenPromise = store.dispatch('refreshToken');
}
await refreshTokenPromise;
refreshTokenPromise = null;
return http(error.config);
};
const updateAuthCb = createUpdateAuthInterceptor(store, axios);
axios.interceptors.response.use(null, updateAuthCb);
$apiUrl = "https://api.shiptor.ru/public/v1";
$apiKey = "YOUR_KEY";
$client = new \JsonRPC\Client($apiUrl);
// Set headers
$client->getHttpClient()->withBeforeRequestCallback(function(HttpClient $client, $payload) {
$client->withHeaders([
"Content-Type: application/json",
"x-authorization-token: {$apiKey}"
]);
});
// Fetch something
$method = "calculateShipping";
$params = ['paramName'=>"paramValue"];
$result = $client->execute($method, $params);
It may be great to have built-in HTTP caching of some kind, but it is way better to use a Content-Delivery Network or a caching proxy server for this, as you will have to do this sooner or later in the production environment.
@Override
@Transactional
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userRepository.findByUserName(userName)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with username: " + userName)
);
UserPrincipal userPrincipal = UserPrincipal.create(user);
logger.info("user with name: {} succesfully loaded", userPrincipal.getUsername());
return userPrincipal;
}
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
public class UserPrincipal implements UserDetails {
static Logger logger = LoggerFactory.getLogger(UserPrincipal.class);
private Long id;
private String name;
private String username;
private String lastname;
private String middlename;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserPrincipal(Long id, String username, String name, String password, String lastname, String middlename, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.name = name;
this.username = username;
this.lastname = lastname;
this.middlename = middlename;
this.password = password;
this.authorities = authorities;
}
public static UserPrincipal create(User user) {
logger.info(user.toString());
List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
new SimpleGrantedAuthority(role.getRole())
).collect(Collectors.toList());
return new UserPrincipal(
user.getId(),
user.getUserName(),
user.getName(),
user.getPassword(),
user.getLastName(),
user.getMiddleName(),
authorities
);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserPrincipal that = (UserPrincipal) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
String username = loginRequest.getUserName();
String password = loginRequest.getPassword();
Authentication authentication;
try {
authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
username,
password
)
);
} catch (AuthenticationException e) {
logger.error("Invalid username/password supplied");
throw new BadCredentialsException("Invalid username/password supplied");
}
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}